//
//  TiJiaoDingDanViewController.m
//  XiangMu
//
//  Created by 康世标 on 15/8/6.
//  Copyright (c) 2015年 康世标. All rights reserved.
//
#import "WoDeDingDanViewController.h"
#import "TiJiaoDingDanViewController.h"

@interface TiJiaoDingDanViewController ()

@end

@implementation TiJiaoDingDanViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.tableView1 reloadData];
    
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"选择支付方式";
    self.tableView1.separatorColor=[UIColor clearColor];
    self.tableView1.backgroundColor=CL_BGCOLOR;

    self.couponId = -1;
    self.select = 0;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notfiction) name:@"kfc" object:nil];
    
    [self getYouHuiJuan];
}

- (void)notfiction{
    
    NSLog(@"支付成功了");
//    
    WoDeDingDanViewController * w = [[WoDeDingDanViewController alloc]init];
    
    [self.navigationController pushViewController:w animated:YES];
    
}
- (void)getYouHuiJuan{
    hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"数据加载中";
    
    [QingQiuShuJu getWoDeYouHuiJuan:[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"] Block:^(NSDictionary *dic, BOOL isOK)
     {
         if (isOK) {
             
             if ([[dic valueForKey:@"status"]intValue]==200) {
                 
                 self.dataArr = [dic valueForKey:@"data"];
                 
                 [self.dataArr enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL *stop) {
                     
                     self.num = [[obj valueForKey:@"num"] intValue]+self.num;
                     
                     
                 }];
              
                 [self.tableView1 reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
                 
                 [hud setHidden:YES];
                 hud.removeFromSuperViewOnHide =YES;
             }
             else{
                 
                 hud.mode = MBProgressHUDModeText;
                 hud.labelText = [dic valueForKey:@"msg"];
                 hud.removeFromSuperViewOnHide = YES;
             }
         }
         else{
             hud.mode = MBProgressHUDModeText;
             hud.labelText = @"网络连接错误";
             
             hud.removeFromSuperViewOnHide = YES;
         }
         
     }];
    

    
    
}

#pragma mark---UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return 1;
    }
    else if (section==1)
    {
        return 1;
    }
    else{
        
        return 1 ;
    }
  
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0) {
        
        DingDanJiaGeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"dingdan"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DingDanJiaGeTableViewCell" owner:nil options:nil]lastObject];
            
        }
        
        if ([[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]==[NSNull null])
        {
            cell.preic.text = [NSString stringWithFormat:@"￥%@",[[self.dataDic valueForKey:@"order"] valueForKey:@"price"]];
        }
        else{
            cell.preic.text = [NSString stringWithFormat:@"￥%@",[[self.dataDic valueForKey:@"order"] valueForKey:@"price"]];
        }
        
        return cell;
        
        
    }
    
   else if (indexPath.section==1)
   {
        YouHuiJuanTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"youhuijuan"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"YouHuiJuanTableViewCell" owner:nil options:nil]lastObject];
            
        
        }
       
       if ([[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]==[NSNull null])
       {
           cell.page.text = [NSString stringWithFormat:@"%ld张可用",(long)self.num];
           cell.preicYh.text = [NSString stringWithFormat:@"￥%ld",(long)self.price];
           if (self.woDeDingDan) {
               cell.imageView1.hidden = YES;
           }
       }
       else{
           
           cell.preicYh.text = [NSString stringWithFormat:@"￥%@",[[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]];
           
           cell.imageView1.hidden = YES;
       }

       
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else{
        FuKuanFangShiTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"fukuangfangshi1"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"FuKuanFangShiTableViewCell" owner:nil options:nil]lastObject];
        }
        
  
        
        [cell.weiXinBtn addTarget:self action:@selector(btnColck:) forControlEvents:UIControlEventTouchUpInside];
        [cell.zhiFuBaoBtn addTarget:self action:@selector(btnColck:) forControlEvents:UIControlEventTouchUpInside];
        [cell.xianXiaBtn addTarget:self action:@selector(btnColck:) forControlEvents:UIControlEventTouchUpInside];
         cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.queRenBtn.backgroundColor = CL_00cc85;
        [cell.queRenBtn addTarget:self action:@selector(queRenBtnClock:) forControlEvents:UIControlEventTouchUpInside];
        if ([[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]==[NSNull null])
        {
              cell.preicZy.text =[NSString stringWithFormat:@"￥%d",[[[self.dataDic valueForKey:@"order"] valueForKey:@"price"] intValue]-self.price];
        }
        else{
            
              cell.preicZy.text =[NSString stringWithFormat:@"￥%d",[[[self.dataDic valueForKey:@"order"] valueForKey:@"price"] intValue]-[[[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]intValue]];
        }
        

      
        
        return cell;
    }

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 44.0f;
    }
    else if(indexPath.section==1)
    {
        return  44.0f;
    }
    else{
        return  219.0f;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }
    return 10.0f;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]!=[NSNull null]){
        
        return;
    }
    if (indexPath.section==1) {
        if (self.woDeDingDan) {
            
            return;
        }
        YouHuiJuanViewController*y=[[YouHuiJuanViewController alloc]init];
        y.price = ^(NSDictionary * prece){
            
            
            self.price = [prece valueForKey:@"money"]==[NSNull null]?0:[[prece valueForKey:@"money"] intValue];
            self.couponId = [prece valueForKey:@"couponId"]==[NSNull null]?-1:[[prece valueForKey:@"couponId"] intValue];
            
            
            
        };
        [self.navigationController pushViewController:y animated:YES];
    }
    
}
- (void)btnColck:(UIButton *)btn{
   

    FuKuanFangShiTableViewCell * cell = (FuKuanFangShiTableViewCell *) [self.tableView1 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    
    switch (btn.tag) {
        case 0:
        {
            cell.imageView1.image = [UIImage imageNamed:@"duogou"];
            cell.imageView2.image = [UIImage imageNamed:@"frame.png"];
            cell.imageView3.image = [UIImage imageNamed:@"frame.png"];

        }
            break;
        case 1:
        {
            cell.imageView1.image = [UIImage imageNamed:@"frame.png"];
            cell.imageView2.image = [UIImage imageNamed:@"duogou"];
            cell.imageView3.image = [UIImage imageNamed:@"frame.png"];
        }
            break;
        case 2:
        {
            cell.imageView1.image = [UIImage imageNamed:@"frame.png"];
            cell.imageView2.image = [UIImage imageNamed:@"frame.png"];
            cell.imageView3.image = [UIImage imageNamed:@"duogou"];
        }
            break;
        default:
            break;
    }
   //
    self.select =(int) btn.tag;
    

}
- (void)queRenBtnClock:(UIButton *)sender
{
    
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"数据加载中...";
    
   
    
//    switch (self.select)
//    {
//        case 0:
//        {
//                 }
//            break;
//        case 1:
//        {
//           
//        }
//            break;
//        case 2:
//        {
//           
//        }
//            break;
//            
//        default:
//            break;
//    }
    [self WXyuZhiFuXinXi];

}
//生成预支付信息Wx
- (void)WXyuZhiFuXinXi{
    
    NSMutableDictionary * wxDic =[[NSMutableDictionary alloc]initWithCapacity:0];
    //    订单id
    [wxDic setObject:[[self.dataDic valueForKey:@"order"] valueForKey:@"id"]  forKey:@"orderId"];
    //    价格
    if (self.woDeDingDan) {

        int zong =[[[self.dataDic valueForKey:@"order"] valueForKey:@"price"] intValue];
        
        int wo =[[[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"]==[NSNull null]?0:[[self.dataDic valueForKey:@"order"] valueForKey:@"cheapPrice"] intValue];
        
        int Id;
        
        if ([[self.dataDic valueForKey:@"order"] valueForKey:@"couponId"]==[NSNull null])
        {
            Id = -1;
            
        }
        else{
            Id =[[[self.dataDic valueForKey:@"order"] valueForKey:@"couponId"] intValue];
            
        }
        
//        NSLog(@"--%d--%d",zong,wo);
        [wxDic setObject:@(zong-wo) forKey:@"payPrice"];
        [wxDic setObject:@(Id) forKey:@"couponId"];
        
//        [wxDic setObject:@([[[self.dataDic valueForKey:@"order"] valueForKey:@"couponId"]==[NSNull null]?0:[[self.dataDic valueForKey:@"order"] valueForKey:@"couponId"] intValue]) forKey:@"couponId"];
    }
    else{
        [wxDic setObject: @([[[self.dataDic valueForKey:@"order"] valueForKey:@"price"] intValue]-self.price) forKey:@"payPrice"];
         [wxDic setObject:@(self.couponId ) forKey:@"couponId"];
    }
    
    //    优惠劵Id
    
   
    //    用户id
    long ueseId =[[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"] integerValue];
    
    [wxDic setObject:@(ueseId) forKey:@"userId"];
    
    
    if (self.select == 0)
    {
        [QingQiuShuJu getHuoQuZhiFuXinXI:wxDic block:^(NSDictionary *dic, BOOL isOK) {
            
            if (isOK) {
                
                
                if ([[dic valueForKey:@"status"] intValue]==200)
                {
                    
                    
                   [self weiXin:[dic  valueForKey:@"data"]];
                    
                    
                    [hud hide:YES];
                    
                }
                else{
                    
                    hud.mode = MBProgressHUDModeText;
                    
                    hud.labelText = [dic valueForKey:@"msg"];
                    [hud hide:YES afterDelay:2];
                }
                
            }
            else{
                hud.mode = MBProgressHUDModeText;
                
                hud.labelText = @"连接失败..";
                [hud hide:YES afterDelay:2];
            }
        }];

        
    }
    else if (self.select ==1)
    {
        [QingQiuShuJu zhiFuBao:wxDic block:^(NSDictionary *dic, BOOL isOK) {
         
        
            
            if (isOK) {
                
                
                if ([[dic valueForKey:@"status"] intValue]==200)
                {
                 
                  [self zhiFuBao:[dic valueForKey:@"data"]];
                  
                    
                    [hud hide:YES];
                    
                }
                else
                {
                    
                    hud.mode = MBProgressHUDModeText;
                    
                    hud.labelText = [dic valueForKey:@"msg"];
                    [hud hide:YES afterDelay:2];
                }
                
            }
            else
            {
                hud.mode = MBProgressHUDModeText;
                
                hud.labelText = @"连接失败..";
                [hud hide:YES afterDelay:2];
            }
        
        }];
    }
    else{
        
//        线下支付
        
        [self xianXiaZhiFu:wxDic];
        
    }
}
//调用微信支付
- (void)weiXin:(NSDictionary *)dic
{
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = @"1263837101";
    request.prepayId= [dic valueForKey:@"prepayid"];
    
    request.package = @"Sign=WXPay";
    request.nonceStr= [dic valueForKey:@"nonceStr"];
    
    request.timeStamp= [[dic valueForKey:@"timeStamp"] intValue];
    request.sign = [dic valueForKey:@"paySign"];
    
    
    DataMD5 *md5 = [[DataMD5 alloc] init];
    
    request.sign=[md5 createMD5SingForPay:[dic valueForKey:@"appId"] partnerid:request.partnerId prepayid:request.prepayId package:request.package noncestr:request.nonceStr timestamp:request.timeStamp];
    NSLog(@"request---%@",request);
    //            调用微信
    
//   [WXApi handleOpenURL:[NSURL URLWithString:@""] delegate:self];
    
    if (![WXApi isWXAppInstalled]) {
        
        [[[UIAlertView alloc]initWithTitle:@"请安装微信客户端" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]show];
    }
    
    [WXApi sendReq:request];
}
//调起支付宝支付
- (void)zhiFuBao:(NSString *)orderString{
    
    NSLog(@"---%@",orderString);
    
     NSString *appScheme = @"alisdkdemo";
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        
        if ([[resultDic valueForKey:@"resultStatus"]isEqualToString:@"9000"])
        {
            
          //支付成功
           
            [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil]show];
        }
        else{
            
               [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil]show];
        }
    }];

}
//线下支付
- (void)xianXiaZhiFu:(NSDictionary *)dic1{
    
    [QingQiuShuJu xianXiaZhiFu:dic1 block:^(NSDictionary *dic, BOOL isOK) {
        
        if (isOK) {
            
//            NSLog(@"---%@",dic);
            if ([[dic valueForKey:@"status"] intValue]==200) {
                
                NSLog(@"线下支付成功");
                        [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功如有疑问请联系客服" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil]show];
            }
            else{
                
                [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:[dic valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil]show];
                
                
                
            }
            
            
        }
        else{
             [[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"网络连接错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil]show];
        }
    }];
}
#pragma mark --- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==1) {
        
        return;
    }
    
     [[NSNotificationCenter defaultCenter]postNotificationName:@"kfc" object:self];
    
}


//- (void)weiXin{
//    
//    NSString *appid,*mch_id,*nonce_str,*sign,*body,*out_trade_no,*total_fee,*spbill_create_ip,*notify_url,*trade_type,*partner;
//    //应用APPID
//    appid =@"wx96e5e4d6c0c6a2f8";
//    //微信支付商户号
//    mch_id =@"1263837101";
//    ///产生随机字符串，这里最好使用和安卓端一致的生成逻辑
//    nonce_str =[self generateTradeNO];
//    body =@"16G白色";
//    //随机产生订单号用于测试，正式使用请换成你从自己服务器获取的订单号
//    out_trade_no = [self getOrderNumber];
//    //交易价格1表示0.01元，10表示0.1元
//    total_fee = @"1";
//    //获取本机IP地址，请再wifi环境下测试，否则获取的ip地址为error，正确格式应该是8.8.8.8
//    spbill_create_ip =[getIPhoneIP getIPAddress];
//    //交易结果通知网站此处用于测试，随意填写，正式使用时填写正确网站
//    notify_url =@"http://www.baidu.com";
//    trade_type =@"APP";
//    //商户密钥
//    partner = @"aipeihuaipeihuaipeihuaipeihuaipe";
//    //获取sign签名
//    DataMD5 *data = [[DataMD5 alloc] initWithAppid:appid mch_id:mch_id nonce_str:nonce_str partner_id:partner body:body out_trade_no:out_trade_no total_fee:total_fee spbill_create_ip:spbill_create_ip notify_url:notify_url trade_type:trade_type];
//    sign = [data getSignForMD5];
//    //设置参数并转化成xml格式
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setValue:appid forKey:@"appid"];//公众账号ID
//    [dic setValue:mch_id forKey:@"mch_id"];//商户号
//    [dic setValue:nonce_str forKey:@"nonce_str"];//随机字符串
//    
//    
//    [dic setValue:sign forKey:@"sign"];//签名nonce_str
//    [dic setValue:body forKey:@"body"];//商品描述
//    [dic setValue:out_trade_no forKey:@"out_trade_no"];//订单号
//    [dic setValue:total_fee forKey:@"total_fee"];//金额
//    [dic setValue:spbill_create_ip forKey:@"spbill_create_ip"];//终端IP
//    [dic setValue:notify_url forKey:@"notify_url"];//通知地址
//    [dic setValue:trade_type forKey:@"trade_type"];//交易类型
//    
//    NSString *string = [dic XMLString];
//    
//    [self http:string];
//
//}
//- (void)http:(NSString *)xml{
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    //这里传入的xml字符串只是形似xml，但是不是正确是xml格式，需要使用af方法进行转义
//    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
//    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"https://api.mch.weixin.qq.com/pay/unifiedorder" forHTTPHeaderField:@"SOAPAction"];
//    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
//        return xml;
//    }];
//    //发起请求
//    [manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder" parameters:xml success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
//        NSLog(@"responseString is %@",responseString);
//        //将微信返回的xml数据解析转义成字典
//        NSDictionary *dic = [NSDictionary dictionaryWithXMLString:responseString];
//        NSLog(@"dic--%@",dic);
//        //判断返回的许可
//        if ([[dic objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] &&[[dic objectForKey:@"return_code"] isEqualToString:@"SUCCESS"] ) {
//                       //发起微信支付，设置参数
//            PayReq *request = [[PayReq alloc] init];
//            request.partnerId = [dic objectForKey:@"mch_id"];
//            request.prepayId= [dic objectForKey:@"prepay_id"];
//            request.package = @"Sign=WXPay";
////            request.openID=@"wx96e5e4d6c0c6a2f8";
//            request.nonceStr= [dic objectForKey:@"nonce_str"];
//               //将当前事件转化成时间戳
//            NSDate *datenow = [NSDate date];
//            NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
//            UInt32 timeStamp =[timeSp intValue];
//            request.timeStamp= timeStamp;
//            DataMD5 *md5 = [[DataMD5 alloc] init];
//            
//            request.sign=[md5 createMD5SingForPay:@"wx96e5e4d6c0c6a2f8" partnerid:request.partnerId prepayid:request.prepayId package:request.package noncestr:request.nonceStr timestamp:request.timeStamp];
//            NSLog(@"---%@",request);
//            //            调用微信
//            [WXApi sendReq:request];
//            
//        }else
//        {
//            NSLog(@"参数不正确，请检查参数");
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"error is %@",error);
//    }];
//}
//#pragma mark 微信支付
/////产生随机字符串
//- (NSString *)generateTradeNO
//{
//    static int kNumber = 15;
//    
//    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRST";
//    NSMutableString *resultStr = [[NSMutableString alloc] init];
//    srand(time(0));
//    for (int i = 0; i < kNumber; i++)
//    {
//        unsigned index = rand() % [sourceStr length];
//        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
//        [resultStr appendString:oneStr];
//    }
//    return resultStr;
//}
////将订单号使用md5加密
//-(NSString *) md5:(NSString *)str
//{
//    const char *cStr = [str UTF8String];
//    unsigned char result[16]= "0123456789abcdef";
//    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
//    return [NSString stringWithFormat:
//            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
//            result[0], result[1], result[2], result[3],
//            result[4], result[5], result[6], result[7],
//            result[8], result[9], result[10], result[11],
//            result[12], result[13], result[14], result[15]
//            ];
//    
//}
////产生随机数
////用于测试
//- (NSString *)getOrderNumber{
//    int random = arc4random()%10000;
//    return [self md5:[NSString stringWithFormat:@"%d",random]];
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
